import { Extdata, ExtObjItem } from "../../rule3d"
import ExtObj from "./ExtObj"
import T from "../math/19674"
export default {
  deserialize: (data: ExtObjItem[]) => {
    const action = <T extends keyof ExtObjItem>(item: ExtObjItem, sourcekey: T, extobj: ExtObj, targetKey: T, func?: (e: ExtObjItem[T]) => any) => {
      const val = item[sourcekey]
      if (void 0 !== val) extobj[targetKey] = func ? func(val) : val
      else {
        throw Error(`Required property missing in data: ${sourcekey}`)
      }
    }
    const extdataAction = (data: Extdata) => {
      return { ...data, info: data.info ? { ...data.info, custom: JSON.parse(data.info.custom) } : null }
    }
    if (!data || Object.keys(data).length < 1) return null
    const result: Record<string, ExtObj> = {}

    try {
      for (const item of data) {
        const extobj = new ExtObj()
        action(item, "quaternion", extobj, "quaternion", e => T.ep.fromVisionQuaternion(e))
        action(item, "position", extobj, "position", e => T.ep.fromVisionVector(e))
        action(item, "scale", extobj, "scale", e => T.ep.fromVisionVector(e))
        action(item, "extdata", extobj, "extdata", e => extdataAction(e))
        action(item, "contentType", extobj, "contentType")
        action(item, "discripe", extobj, "discripe")
        action(item, "enable", extobj, "enable")
        action(item, "followCamera", extobj, "followCamera")
        action(item, "gif", extobj, "gif")
        action(item, "info", extobj, "info")
        action(item, "location", extobj, "location")
        action(item, "mtl", extobj, "mtl")
        action(item, "music", extobj, "music")
        action(item, "name", extobj, "name")
        action(item, "obj", extobj, "obj")
        action(item, "occupiedFodder", extobj, "occupiedFodder")
        action(item, "opacity", extobj, "opacity")
        action(item, "packTexture", extobj, "packTexture")
        action(item, "picturesId", extobj, "picturesId")
        action(item, "positionId", extobj, "positionId")
        action(item, "quaternionId", extobj, "quaternionId")
        action(item, "scaleId", extobj, "scaleId")
        action(item, "scaling", extobj, "scaling")
        action(item, "text", extobj, "text")
        action(item, "texture", extobj, "texture")
        action(item, "type", extobj, "type")
        action(item, "x0", extobj, "x0")
        action(item, "x1", extobj, "x1")
        action(item, "y0", extobj, "y0")
        action(item, "y1", extobj, "y1")
        action(item, "id", extobj, "id")
        result[item.id] = extobj
      }
    } catch (e) {
      console.error("Error reading sweeps list", e)
    }
    return Object.keys(result).length ? result : null
  }
}
